<template>
  <div style="margin-top:30px">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" label-width="150px" style="margin-right:15px">
              <el-input v-model="form.shipmentName" placeholder="请选择商品分类" style="width:100%" :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <!--<el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品分类" style="margin-right:15px" prop="type" label-width="110px">
              <el-select v-model="form.type" placeholder="请输入商品分类 " style="width:100%" clearable>
                <el-option
                  v-for="item in typeData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>-->
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品分类" style="margin-right:15px"  label-width="150px">
              <el-input v-model="form.typeName" placeholder="请选择商品分类" style="width:100%" :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品编码" style="margin-right:15px" prop="goodCode" label-width="150px">
              <el-input v-model.trim="form.goodCode" placeholder="请输入商品编码" style="width:100%" maxlength="100" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品条码" style="margin-right:15px" prop="barCode" label-width="150px">
              <el-input v-model.trim="form.barCode" placeholder="请输入商品条码" style="width:100%" maxlength="100" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品名称" style="margin-right:15px" prop="name" label-width="150px">
              <el-input v-model="form.name" placeholder="请输入商品名称" style="width:100%"  maxlength="100" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="基本单位" style="margin-right:15px" prop="unitCode" label-width="150px">
              <el-select v-model="form.unitCode" placeholder="请输入基本单位" style="width:100%" @change='getUnitCode($event)'>
                <el-option
                  v-for="item in unitList"
                  :key="item.code"
                  :label="item.unitName"
                  :value="item.code"
                />
              </el-select>

            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
<!--        <el-col :span="12">-->
<!--          <div class="grid-content bg-purple">-->
<!--            <el-form-item label="基本单位精度" style="margin-right:15px" prop="unitPrecision" label-width="150px">-->
<!--              <el-input v-model="form.unitPrecision" placeholder="请输入基本单位精度" style="width:100%"/>-->
<!--            </el-form-item>-->
<!--          </div>-->
<!--        </el-col>-->
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="规格" style="margin-right:15px" prop="spec" label-width="150px">
              <el-input v-model="form.spec" placeholder="请输入规格" style="width:100%" maxlength="100" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="批次规则" style="margin-right:15px" prop="lotNumber" label-width="150px">
              <el-select v-model="form.lotNumber" placeholder="请输入批次规则" style="width:100%">
                <el-option
                  v-for="item in batchRuleList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <!--<el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品类型" style="margin-right:15px" prop="typeCode" label-width="110px">
              <el-input v-model="form.typeCode" placeholder="请输入商品类型" style="width:100%"/>
            </el-form-item>
          </div>
        </el-col>-->
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="商品类型" style="margin-right:15px" prop="type" label-width="150px">
              <el-select v-model="form.type" placeholder="请选择商品类型 " style="width:100%" clearable>
                <el-option
                  v-for="item in typeData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="保质期（天）" style="margin-right:15px" prop="quality" label-width="150px">
              <el-input v-model="form.quality" placeholder="请输入保质期（天）" style="width:100%" maxlength="20" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="临期预警（天）" style="margin-right:15px" prop="earlyWarning" label-width="150px">
              <el-input v-model="form.earlyWarning" placeholder="请输入临期预警（天）" style="width:100%" maxlength="20" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="收货预警（天）" style="margin-right:15px" prop="receivingWarning" label-width="150px">
              <el-input v-model="form.receivingWarning" placeholder="请输入收货预警（天）" style="width:100%" maxlength="20" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="发货预警（天）" style="margin-right:15px" prop="sendWarning" label-width="150px">
              <el-input v-model="form.sendWarning" placeholder="请输入发货预警（天）" style="width:100%" maxlength="20" show-word-limit/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="混放策略" style="margin-right:15px"  label-width="150px" prop="storageStrategy">
              <el-select v-model="form.storageStrategy" placeholder="请输入混放策略 " style="width:100%" clearable>
                <el-option
                  v-for="item in storageStrategyTypeData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="品牌" style="margin-right:15px" prop="brandCode" label-width="150px">
              <el-select v-model="form.brandCode" placeholder="请输入品牌" style="width:100%">
                <el-option
                  v-for="item in brandList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>

            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div style="margin-top: 20px; margin-left: 70px; margin-bottom:50px">
            <el-checkbox v-model="form.sale" label="可销售"></el-checkbox>
            <el-checkbox v-model="form.purchase" label="可采购"></el-checkbox>
          </div>
        </el-col>
      </el-row>
    <vxe-toolbar id="toolbar_demo3">
      <!-- XYTODO TODO 20201119 下一步需要支持相同单位但转换量不同的单位，但这样对后面各种操作影响较多，改动量较大，先暂时屏蔽新增操作，避免同一商品多条相同单位对后面的问题 -->
     <!-- <template v-slot:buttons>
        <el-button @click="insertEvent">新增</el-button>
      </template>-->
    </vxe-toolbar>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      @edit-actived="editActivedEvent"
      show-footer
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <template v-slot:empty>
        <p> </p>
      </template>
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="unitName" title="单位名称"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.unitName" placeholder="请输入单位" filterable style="width:100%" @change="nameChangeEvent(row)" :disabled="unitNameDisabled">
            <el-option
              v-for="item in goodsUnitList"
              :key="item.unitName"
              :label="item.unitName"
              :value="item.unitName"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column field="unitNum" title="单位编码" width="120"></vxe-table-column>
      <vxe-table-column field="quantity" title="件装量"  width="120" :edit-render="{name: 'input',attrs: {disabled: quantityDisabled}}"></vxe-table-column>
      <vxe-table-column field="length" title="长（m）"  width="120" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="width" title="宽（m）" :edit-render="{name: 'input'}" width="120"></vxe-table-column>
      <vxe-table-column field="height" title="高（m）" width="120" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="weight" title="重量（kg）"   width="120" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column field="volume" title="体积（m³）" width="120" :edit-render="{name: 'input'}"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="50">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="$refs.xTable.remove(scope.row)" v-if="scope.row.isShow !== 1">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import { goodsEdit, findUnitByShipmentCode, findBatchRuleByShipmentCode, findBrandByShipmentCode,goodsDetail,findGoodsUnit} from '@/api/basicInfo'
import shipmentSelect from '@/views/components/shipmentSelect.vue'

Vue.use(VXETable)
export default {
  components: {
    shipmentSelect
  },
  props: {
    operationTypeCode: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      unitCodeDisabled: false,
      unitNameDisabled: false,
      quantityDisabled: false,
      allAlign:'center',
      unitList:[],                  //基础单位数据
      brandList:[],                  //品牌数据
      batchRuleList:[],                  //批次规则数据
      goodsUnitList:[],
      storageStrategyTypeData:[   //混放策略列表
        { code: "0", name: "商品混放" },
        { code: "1",name: "批次混放" },
        { code: "2",name: "混放" },
        { code: "3",name: "不混放" },
      ],
      typeData:[   //商品分类列表
        { code: "0", name: "原料" },
        { code: "1",name: "成品" },
        { code: "2",name: "半成品" },
      ],

      tableData:[
      ],
      form: {
        barCode:'',                 //商品条码 ,
        brandCode:'',               //品牌code ,
        code:'',                    //数据标识 ,
        earlyWarning:'',            //临期预警 ,
        gmtModified:'',             //修改时间 ,
        gmt_created:'',             //创建时间 ,
        goodCode:'',                //商品编码 ,
        lotNumber:'',               //批号 ,
        purchase: false,
        sale:false,
        typeName:"",
        shipmentName:'',
        storageStrategy:'',
        goodsUnitConversionList:[],
        name:'',                    //商品名称 ,
        quality:'',                 //保质期 ,
        receivingWarning:'',        //收货预警 ,
        sendWarning:'',             //发货预警 ,
        shipmentCode:'',            //所属入驻商 ,
        spec:'',                    //规格 ,
        stockType:'',               //库存类型 ,
        typeCode:'',                //商品类型 ,
        unitCode:'',                //单位code ,
        unitPrecision:'',           //单位精度 ,
      },
        rules: {
          type: [
            {required: true, message: '请输入商品分类', trigger: 'blur'},
          ],
          goodCode: [
            {required: true, message: '请输入商品编码', trigger: 'blur'},
              { min: 1, max: 100, message: '商品编码长度不能大于100', trigger: 'blur' }
          ],
          barCode: [
            {required: true, message: '请输入商品条码', trigger: 'blur'},
              { min: 1, max: 100, message: '商品条码长度不能大于100', trigger: 'blur' }
          ],
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
              { min: 1, max: 100, message: '商品名称长度不能大于100', trigger: 'blur' }
          ],
            spec: [
                {required: false, message: '', trigger: 'blur'},
                { min: 0, max: 100, message: '规格长度不能大于100', trigger: 'blur' }
            ],
          unitCode: [
            {required: true, message: '请输入基本单位', trigger: 'blur'},
          ],
          lotNumber: [
            {required: true, message: '请输入批次规则', trigger: 'blur'},
          ],
          typeCode: [
            {required: true, message: '请输入商品类型', trigger: 'blur'},
          ],
          quality: [
            {required: true, message: '请输入保质期（天）', trigger: 'blur'},
              {pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '保质期格式错误！', trigger: 'blur'}
          ],
          receivingWarning: [
            {required: false, message: '请输入收货预警（天）', trigger: 'blur'},
              {pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '收货预警格式错误！', trigger: 'blur'}
          ],
          sendWarning: [
            {required: false, message: '请输入发货预警（天）', trigger: 'blur'},
            {pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '发货预警格式错误！', trigger: 'blur'}
          ],
          earlyWarning: [
            {required: false, message: '请输入临期预警（天）', trigger: 'blur'},
            {pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '临期预警格式错误！', trigger: 'blur'}
          ],
          storageStrategy: [
            {required: true, message: '请输入混放策略', trigger: 'blur'},
          ],
          shipmentCode: [
            {required: true, message: '请选择所属入驻商', trigger: 'blur'},
          ],
        },
        validRules: {
          unitName: [
            { required: true, message: '单位编码必须填写' },
          ],
          length: [
            { required: false, message: '长（m）必须填写' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多10位数字并且最多保留2位小数' },
            { max: 14, message: '最多10位数字并且最多保留2位小数'}
          ],
          width: [
            { required: false, message: '宽（m）必须填写' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多10位数字并且最多保留2位小数' },
            { max: 14, message: '最多10位数字并且最多保留2位小数'}
          ],
          height: [
            { required: false, message: '高（m）必须填写' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多10位数字并且最多保留2位小数' },
            { max: 14, message: '最多10位数字并且最多保留2位小数'}
          ],
          weight: [
            { required: false, message: '重量（kg）必须填写' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多10位数字并且最多保留2位小数' },
            { max: 14, message: '最多10位数字并且最多保留2位小数'}
          ],
          volume: [
            { required: false, message: '体积（m³）必须填写' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多10位数字并且最多保留2位小数' },
            { max: 14, message: '最多10位数字并且最多保留2位小数'}
          ],

          quantity: [
            { required: true, message: '件装量必须填写' },
            { pattern: /^[1-9]+[0-9]*$/, message: '数量为大于0的正整数' }
          ],
        },
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    // 获取页面信息
    getInfo() {
      goodsDetail(this.operationTypeCode).then(response => {
          this.form = response.data
          if(this.form.purchase == 0){
            this.form.purchase = false
          }
          if(this.form.purchase == 1){
            this.form.purchase = true
          }
          if(this.form.sale == 0){
            this.form.sale = false
          }
          if(this.form.sale == 1){
            this.form.sale = true
          }
          this.tableData = response.data.units
          this.tableData.forEach( i => {
            if(i.unitCode == this.form.unitCode && i.quantity ==1){
              i.isShow = 1
            }
          })
        findUnitByShipmentCode(response.data.shipmentCode).then(response => {
          this.unitList = response.data
        })
        findBrandByShipmentCode(response.data.shipmentCode).then(response => {
          this.brandList = response.data
        })
        findBatchRuleByShipmentCode(response.data.shipmentCode).then(response => {
          this.batchRuleList = response.data
        })
        findGoodsUnit(response.data.shipmentCode).then(response => {
          this.goodsUnitList = response.data
        })
      })
    },
    //计算基本单位
    nameChangeEvent (row) {
      const sd = this.goodsUnitList.find(i => i.unitName == row.unitName)
      row.unitCode = sd.code
      row.unitNum = sd.unitCode
    },

    getUnitCode(e){
      const sd = this.unitList.find(i => i.code == e)
      console.log(sd)
      this.tableData.forEach( i => {
        if(i.isShow ==1){
          i.unitNum = sd.unitCode
          i.unitName = sd.unitName
          i.unitCode = sd.code
        }
      })
    },
    // 新增
    insertEvent () {
      const xTable = this.$refs.xTable
      xTable.insert().then(({ row }) => xTable.setActiveRow(row))
    },
    // // 提交
    // funcSubmit() {
    //   const data = this.form
    //   this.$refs['form'].validate((valid) => {
    //     if (valid) {
    //       this.isDisable = true
    //       goodsAdd(data).then(response => {
    //         this.$message({ message: response.msg, type: 'success' })
    //         this.$emit('fatherAddMethod')
    //         this.form = {}
    //       }).catch(() => this.isDisable = false)
    //     } else {
    //       return false
    //     }
    //   })
    // },
    // 提交
    async funcSubmit() {
      const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
      if (errMap) {
        return this.$message.error('长宽高最多10位数字并且最多保留2位小数')
      }
      let arr = this.form
      for(let key in arr ){
        if(arr[key] === false){
          arr[key] = 0
        }
        if(arr[key] === true){
          arr[key] = 1
        }
      }
      arr.goodsUnitConversionList = this.$refs.xTable.tableData

      const data = arr
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
            // this.$refs.xTable.validate((valids) => {
            //   if(valids){
                this.isDisable = true
                goodsEdit(data).then(response => {
                  this.$message({ message: response.msg, type: 'success' })
                  this.$emit('fatherEditMethod')
                  this.isDisable = false
                }).catch(() => this.isDisable = false)
            //   }else {
            //     return false
            //   }
            // })
          } else {
            return false
          }
        })
    },
    //禁用
    editActivedEvent ({ rowIndex, row }) {
      this.unitCodeDisabled = row.isShow == 1
      this.unitNameDisabled = row.isShow == 1
      this.quantityDisabled = row.isShow == 1

    },
    // 取消
    funcCancel() {
      this.$emit('fatherCancelMethod', 'edit')
    }
  }
}
</script>
<style lang="scss" scoped >
  .dialog-footer {
    margin: 15px 0 15px 0;
    width: 90px;
    float: right;
  }
</style>
